/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    vector<vector<int> > levelOrder(TreeNode *root) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        if (root == NULL) {
            return vector<vector<int> >();
        }
        queue<TreeNode *> q;
        vector<vector<int> > ans;

        q.push(root);
        while (!q.empty()) {
            int n = q.size();
            vector<int> line;

            for (int i = 0; i < n; ++i) {
                TreeNode *node = q.front();
                q.pop();
                line.push_back(node->val);
                if (node->left) {
                    q.push(node->left);
                }
                if (node->right) {
                    q.push(node->right);
                }
            }
            ans.push_back(line);
        }
        return ans;
    }
};
